const express = require('express')
const router = express.Router()
const Chat = require('../models/Chat.js')
const auth = require('../middleware/auth.js')
const { pool } = require('../config/db.js')
const { deepseekService } = require('../services/deepseek.js')

// 获取聊天历史
router.get('/history', auth, async (req, res) => {
  try {
    const conversations = await Chat.findConversationsByUserId(req.user.userId)
    res.json(conversations)
  } catch (err) {
    console.error('获取聊天历史失败:', err.message)
    res.status(500).json({ message: err.message })
  }
})

// 调试: 获取特定会话的消息
router.get('/debug/messages/:chatId', auth, async (req, res) => {
  try {
    const chatId = parseInt(req.params.chatId)

    if (isNaN(chatId)) {
      return res.status(400).json({ message: '无效的会话ID' })
    }

    // 验证会话所有权
    const [chats] = await pool.query(
      'SELECT * FROM chats WHERE id = ? AND user_id = ?',
      [chatId, req.user.userId]
    )

    if (chats.length === 0) {
      return res.status(404).json({ message: '会话不存在或无权访问' })
    }

    // 查询所有相关消息
    const [messagesAllChatId] = await pool.query(
      'SELECT * FROM messages WHERE chat_id = ? ORDER BY created_at ASC',
      [chatId]
    )

    const [messagesMatchingSessionId] = await pool.query(
      'SELECT * FROM messages WHERE chat_id = ? AND session_id = ? ORDER BY created_at ASC',
      [chatId, chatId]
    )

    res.json({
      chatId,
      totalMessages: messagesAllChatId.length,
      matchingSessionMessages: messagesMatchingSessionId.length,
      messagesWithChatIdOnly: messagesAllChatId,
      messagesWithMatchingSessionId: messagesMatchingSessionId
    })
  } catch (err) {
    console.error('消息调试查询失败:', err)
    res.status(500).json({ message: err.message })
  }
})

// 创建新的会话
router.post('/new-session', auth, async (req, res) => {
  try {
    const { title = '新对话' } = req.body
    const chatId = await Chat.createSession(req.user.userId, title)

    res.json({
      success: true,
      data: {
        chatId,
        title
      }
    })
  } catch (err) {
    console.error('创建会话错误:', err)
    res.status(500).json({
      success: false,
      message: err.message || '创建新会话失败'
    })
  }
})

// 发送消息
router.post('/message', auth, async (req, res) => {
  try {
    const { message, model, temperature, chatId } = req.body

    if (!message) {
      return res.status(400).json({
        success: false,
        message: '消息不能为空'
      })
    }

    let currentChatId = chatId;

    // 如果没有指定chatId，创建新的聊天
    if (!currentChatId) {
      const title = message.slice(0, 50)
      const [result] = await pool.query(
        'INSERT INTO chats (user_id, title) VALUES (?, ?)',
        [req.user.userId, title]
      )
      currentChatId = result.insertId
    }

    // 获取历史消息用于上下文
    const [historicalMessages] = await pool.query(
      'SELECT role, content FROM messages WHERE chat_id = ? AND session_id = ? ORDER BY created_at ASC',
      [currentChatId, currentChatId]
    )

    // 构建消息历史数组
    const messageHistory = historicalMessages.map(msg => ({
      role: msg.role,
      content: msg.content
    }))

    // 添加新的用户消息
    messageHistory.push({
      role: 'user',
      content: message
    })

    // 先保存用户消息到数据库
    await pool.query(
      'INSERT INTO messages (chat_id, role, content, session_id) VALUES (?, ?, ?, ?)',
      [currentChatId, 'user', message, currentChatId]
    )

    // 调用 AI 服务，传入完整的消息历史
    const aiResponse = await deepseekService.chatCompletion(messageHistory, {
      model: model || 'deepseek-chat',
      temperature: temperature || 0.7
    })

    if (aiResponse.success) {
      // 保存 AI 响应消息
      const aiMessageContent = aiResponse.data.choices[0].message.content
      await pool.query(
        'INSERT INTO messages (chat_id, role, content, session_id) VALUES (?, ?, ?, ?)',
        [currentChatId, 'assistant', aiMessageContent, currentChatId]
      )

      // 更新chat的更新时间
      await pool.query(
        'UPDATE chats SET updated_at = CURRENT_TIMESTAMP WHERE id = ?',
        [currentChatId]
      )

      // 返回成功响应
      res.json({
        success: true,
        data: {
          chatId: currentChatId,
          choices: [{
            message: {
              content: aiMessageContent
            }
          }]
        }
      })
    } else {
      throw new Error(aiResponse.error || 'AI 服务响应失败')
    }
  } catch (error) {
    console.error('聊天错误:', error)
    res.status(500).json({
      success: false,
      error: error.message
    })
  }
})

// 删除单个会话
router.delete('/conversation/:chatId', auth, async (req, res) => {
  try {
    const chatId = req.params.chatId
    const userId = req.user.userId

    const result = await Chat.deleteConversation(chatId, userId)

    if (result.success) {
      res.json({
        code: 200,
        message: result.message,
        success: true
      })
    } else {
      res.status(404).json({
        code: 404,
        message: result.message,
        success: false
      })
    }
  } catch (error) {
    console.error('删除会话失败:', error)
    res.status(500).json({
      code: 500,
      message: '服务器错误，删除失败',
      success: false
    })
  }
})

// 批量删除会话
router.post('/conversations/delete', auth, async (req, res) => {
  try {
    const { chatIds } = req.body

    if (!chatIds || !Array.isArray(chatIds) || chatIds.length === 0) {
      return res.status(400).json({
        code: 400,
        message: '无效的会话ID列表',
        success: false
      })
    }

    const result = await Chat.deleteMultipleConversations(chatIds, req.user.userId)

    if (result.success) {
      res.json({
        code: 200,
        message: result.message,
        success: true,
        data: {
          deleted: result.deleted,
          notDeleted: result.notDeleted
        }
      })
    } else {
      res.status(400).json({
        code: 400,
        message: result.message,
        success: false
      })
    }
  } catch (error) {
    console.error('批量删除会话失败:', error)
    res.status(500).json({
      code: 500,
      message: '服务器错误，批量删除失败',
      success: false
    })
  }
})

module.exports = router
